package com.lm.emitter.controller;

import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
public class LogStreamController {

    @GetMapping(value = "/log-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public ResponseBodyEmitter streamLogs() {
        // 创建 ResponseBodyEmitter，默认超时时间60秒，也可以传入自定义超时时间
        ResponseBodyEmitter emitter = new ResponseBodyEmitter();

        // 使用线程池异步推送数据
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    // 关键修改：添加 "data: " 前缀，并用双换行符结尾
                    String sseData = "data: Data chunk " + i + "\n\n";

                    // 显式设置媒体类型（可选但建议）
                    emitter.send(sseData, MediaType.TEXT_EVENT_STREAM);

                    Thread.sleep(1000);
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                emitter.completeWithError(e);
            }
        });
        executor.shutdown();

        return emitter;
    }
}
